<?php
namespace Test\Controller;
use Think\Controller;

class IndexController extends Controller {
	

    public function index(){
      
      header("Content-Type: text/html;charset=utf-8");
    	Vendor('Wxpay.WxPay#JsApiPay');
			$tools = new \JsApiPay();
			
			$input = new \WxPayUnifiedOrder();
			$input->SetMch_id('1348865501');
			$input->SetNonce_str($this->getNonceStr());
			$sign = $input->SetSign();
			dump($sign);
			$xml = $input->ToXml();


			$startTimeStamp = $this->getMillisecond();//请求开始时间

			$url = 'https://apitest.mch.weixin.qq.com/sandboxnew/pay/getsignkey';

			$response = $this->postXmlCurl($xml, $url, false, 6);
			dump($response);
			exit();
      
   
		}

	/**
	 * 以post方式提交xml到对应的接口url
	 */
	private static function postXmlCurl($xml, $url, $useCert = false, $second = 30){		
		$ch = curl_init();
		//设置超时
		curl_setopt($ch, CURLOPT_TIMEOUT, $second);
		curl_setopt($ch,CURLOPT_URL, $url);
		curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
		curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);//严格校验
		//设置header
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		//要求结果为字符串且输出到屏幕上
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
	
		//post提交方式
		curl_setopt($ch, CURLOPT_POST, TRUE);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
		//运行curl
		$data = curl_exec($ch);
		//返回结果
		if($data){
			curl_close($ch);
			return $data;
		} else { 
			$error = curl_errno($ch);
			curl_close($ch);
			echo "curl出错，错误码:$error";
		}
	}

		private static function getMillisecond(){
		//获取毫秒的时间戳
		$time = explode ( " ", microtime () );
		$time = $time[1] . ($time[0] * 1000);
		$time2 = explode( ".", $time );
		$time = $time2[0];
		return $time;
	}
		
	public static function getNonceStr($length = 32){
		$chars = "abcdefghijklmnopqrstuvwxyz0123456789";  
		$str ="";
		for ( $i = 0; $i < $length; $i++ )  {  
			$str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);  
		} 
		return $str;
	}
}